本篇同步發布於Blog:[解題] LeetCode - 26 Remove Duplicates from Sorted Array
LeetCode
26 - Remove Duplicates from Sorted Array
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
輸入1個整數的陣列nums,裡面元素已經從小到大排序,求在nums移除重複的元素,並回傳移除後的陣列長度。題目不能用額外的計算空間。
比如範例輸入的[1, 1, 2],移除重複元素的陣列是[1, 2],並回傳長度2。
用一個count變數,紀錄從i = 1開始往後掃描,和i - 1有相同的值的次數,再用count做位移取代舊的值。最後要回傳的長度 = 原始長度 - count。
比如輸入 [1, 1, 2, 3, 3]
難度為Easy
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int count = 0 ;
int originSize = nums.size();
for(int i = 1 ; i < originSize;++i){
if(nums[i] == nums[i-1]){
count++;
}
nums[i-count] = nums[i];
}
return originSize - count;
}
};
int main() {
Solution sol;
vector<int> nums{1,1,2};
int len = sol.removeDuplicates(nums);
for(int i = 0 ; i < len;++i){
cout << " " << nums[i];
}
cout << endl;
return 0;
}
using System;
namespace LeetCode26
{
public class Solution {
public int RemoveDuplicates(int[] nums) {
int count = 0 ;
int originSize = nums.Length;
for(int i = 1 ; i < originSize;++i){
if(nums[i] == nums[i-1]){
count++;
}
nums[i-count] = nums[i];
}
return originSize - count;
}
}
class Program
{
static void Main(string[] args)
{
Solution sol = new Solution();
int[] nums = new int[]{1,1,2};
int len = sol.RemoveDuplicates(nums);
for(int i = 0 ;i < len;++i){
Console.Write(" " + nums[i]);
}
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/1-99/26.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/1-99/26.cs